package timing.ukulele.filter;

import io.jsonwebtoken.Jwts;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import timing.ukulele.config.JwtProperties;
import timing.ukulele.util.JWtUtil;

public class JwtTokenAuthenticationFilter implements WebFilter {

    private final JwtProperties jwtProperties;

    public JwtTokenAuthenticationFilter(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
        String token = resolveToken(serverWebExchange.getRequest());
        if (StringUtils.hasLength(token)) {
            Authentication authentication = JWtUtil.getAuthentication(token, jwtProperties.getSecretKey());
            if (authentication != null) {
                return webFilterChain.filter(serverWebExchange).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
            }
        }
        return webFilterChain.filter(serverWebExchange);
    }

    private String resolveToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst("X_TOKEN");
        if (StringUtils.hasLength(token))
            return token;
        return null;
    }
}
